package cn.kow.kmall.common.wechat;

import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.core.exception.ServiceException;
import cn.kow.kmall.common.wechat.request.Code2SessionRequest;
import cn.kow.kmall.common.wechat.response.Code2SessionResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2020-03-09 11:38
 * @Modified By:
 */
@Slf4j
public class WeChatApi {

    public static Code2SessionResponse code2Session(Code2SessionRequest request) {
        String code = request.getCode();
        String appId = request.getAppId();
        String secret = request.getSecret();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        log.info(url);
        try {
            RestTemplate restTemplate = new RestTemplate();
            String responseStr = restTemplate.getForObject(url, String.class);
            log.info(responseStr);
            ObjectMapper objectMapper = new ObjectMapper();
            Code2SessionResponse response = objectMapper.readValue(responseStr, Code2SessionResponse.class);
            if (response.getErrCode() == null) {
                response.setErrCode(0);
                response.setErrMsg("");
            }
            log.info("code2Session response={}", response);
            return response;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(KmallResultEnum.WX_WXACODE_ERROR);
        }
    }


}
